import axios from 'axios'
/**
 * 注意：
 * 此redmine功能依赖：
 * *、对1688等excel文件格式有依赖，
 * *、对worknotes中分销商选项列表、项目代号等值有依赖， *
 * 这些外部依赖变化后，需要跟随修改代码
 */

var config = {
  hostname: '',
  apiKey: ''
}

var logger = console

export function setLogger (loggerIn) {
  if (loggerIn) {
    logger = loggerIn
  } else {
    logger = console
  }
}
export async function importordersfwaybill (excelToJson1688, hostname, apiKey) {
  config.hostname = hostname
  config.apiKey = apiKey

  var newOrderList = convertExcelToLogicOrderJsonResult(excelToJson1688)
  if (!newOrderList) {
    logger.error('order list empty')
    return
  }

  var newIssueList = convertOrderListToIssueList(newOrderList)
  if (!newIssueList || newIssueList.length === 0) {
    logger.error('issue list empty')
  }

  return batchUpdateIssueList(newIssueList)
}

// eslint-disable-next-line no-unused-vars
function convertExcelToLogicOrderJsonResult (excelToJson) {
  var baseOrderInfo = {
    from: null, // "suda"
    wnId: null, // worknotes id
    sfWayBillId: null // sf 运单号
  }

  var orderLogicList = []

  try {
    orderLogicList = convertSudaExcelToOrderList(baseOrderInfo, excelToJson)
  } catch (ex) {
    logger.error('suda ex' + ex)
  }

  var orderList = orderLogicList
  logger.log('order count:' + orderList.length + '; suda:' + orderLogicList.length)
  return orderList
}

function convertSudaExcelToOrderList (baseOrderInfo, excelToJson1688) {
  const sheetResult = excelToJson1688

  if (!sheetResult || sheetResult.length === 0) {
    logger.error('suda empty')
    return []
  }

  var orderList = []
  // 传入的已是纯数据，不含标题行
  for (var i = 0; i < sheetResult.length; ++i) {
    const row = sheetResult[i]
    // logger.log("row:"+JSON.stringify(row));

    const newOrderInfo = Object.assign({}, baseOrderInfo)

    newOrderInfo.wnId = row['用户订单号']
    if (!newOrderInfo.wnId) {
      logger.warn('wnId empty, skip')
      continue
    }

    newOrderInfo.sfWayBillId = row['运单号']
    newOrderInfo.from = 'suda'
    orderList.push(newOrderInfo)

    logger.log('order:' + JSON.stringify(newOrderInfo) + '\n')
  }
  return orderList
}

function createQmWayBillIssueByOrderInfo (orderInfo) {
  // 基础的发货单信息
  var baseIssue = {
    // issue单号
    issue_id: null,
    // 自定义字段
    custom_field_values: {
      99: '快递单号'
    }
  }

  var newIssue = Object.assign({}, baseIssue)
  newIssue.issue_id = orderInfo.wnId
  newIssue.custom_field_values[99] = orderInfo.sfWayBillId
  return newIssue
}

// eslint-disable-next-line no-unused-vars
function convertOrderListToIssueList (orderList) {
  var issueList = []
  for (let i = 0; i < orderList.length; ++i) {
    const newIssue = createQmWayBillIssueByOrderInfo(orderList[i])
    issueList.push(newIssue)
  }
  return issueList
}

function updateIssuePromise (newIssue) {
  return new Promise(function (resolve, reject) {
    var issueId = newIssue.issue_id
    var dataParam = {
      issue: newIssue
    }
    axios({
      method: 'put',
      url: config.hostname + '/issues/' + issueId + '.json',
      data: dataParam,
      headers: {
        'X-Redmine-API-Key': config.apiKey
      }
    })
      .then(response => {
        const data = response.data
        // 更新成功，data为空
        logger.info('update issue ok:' + JSON.stringify(newIssue) + ',' + JSON.stringify(data))
        logger.info('------')
        resolve({ isSuccess: true, success: 1, fail: 0 })
      })
      .catch((err, data) => {
        logger.error('ex' + err)
        logger.error('update issue failed:' + JSON.stringify(data))
        logger.info('issue:' + JSON.stringify(newIssue))
        logger.info('------')
        resolve({ isSuccess: false, success: 0, fail: 1 })
      })
  })
}

// eslint-disable-next-line no-unused-vars
async function batchUpdateIssueList (newIssueList) {
  logger.log('\n\n ============= BATCH UPDATE ISSUE =========== \n')

  var createResultList = []
  var totalSuccessCount = 0
  for (let i = 0; i < newIssueList.length; ++i) {
    const createResult = await updateIssuePromise(newIssueList[i])
    createResultList.push(createResult)
    totalSuccessCount += createResult.success
  }

  logger.log('\n ============= RESULT =========== \n')
  logger.log(JSON.stringify(createResultList))
  logger.log('\n success:' + totalSuccessCount + '; total:' + createResultList.length)
  logger.log('===============================')
  return {
    success: totalSuccessCount,
    total: createResultList.length
  }
}
